Imports Microsoft.VisualBasic
Imports System
Imports Cforge.Net
Imports Cforge.Security.Certificates

Namespace ImapClientDemo.Security
	''' <summary>
	''' A custom certificate provider implementing the interface ICertificateChainProvider that allow user to select an appropriate certificate loaded from the local certificate store.
	''' </summary>
	Friend Class CustomCertProvider
		Implements ICertificateChainProvider
		''' <summary>
		''' Validates a certificate and returns a chain object.
		''' </summary>
		''' <param name="info">The request info.</param>
		''' <returns>CertificateChain chain object.</returns>
        Public Function GetChain(ByVal info As CertificateChainProviderRequestInfo) As X509CertificateChain Implements ICertificateChainProvider.GetChain
            ' Load certificates from the local machine.
            Dim my As New CertificateStore("MY")

            ' Retrieve a list of available certificates.
            Dim certs() As X509Certificate
            If info.GetIssuers().Length > 0 Then
                certs = my.GetCertificates(info.GetIssuers(), CertificateSearchType.TimeValid Or CertificateSearchType.HasPrivateKey Or CertificateSearchType.ClientAuthentication)
            Else
                certs = my.GetCertificates(CertificateSearchType.TimeValid Or CertificateSearchType.HasPrivateKey Or CertificateSearchType.ClientAuthentication)
            End If

            ' If no certificate found, return.
            If certs.Length = 0 Then
                Return Nothing
            End If

            ' Show the CertProvider to ask user to choose an appropriate certificate.
            Dim rhForm As New CertProvider()
            ' Load certificates.
            rhForm.LoadData(certs)

            If rhForm.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
                ' If a certificate is selected, the create a new one base on the selected certificate.
                If rhForm.SelectedCertificate IsNot Nothing Then
                    Return X509CertificateChain.Create(rhForm.SelectedCertificate)
                End If
            End If

            ' No certificate is selected, just return nothing.
            Return Nothing
        End Function
	End Class
End Namespace